package edu.wtbu.cs.androiddemo.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class UserInfoDBUtil {

    SQLiteHelper sqLiteHelper ;

    public  UserInfoDBUtil(Context context){
        sqLiteHelper = new SQLiteHelper(context);
    }

    public void insert(String name, String pwd, String nick) {

        SQLiteDatabase database = sqLiteHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("user_name", name);
        values.put("user_pwd", pwd);
        values.put("user_nick", nick);
        long id = database.insert("userinfo", null, values);
        database.close();
    }

    public int delete(String name) {
        SQLiteDatabase database = sqLiteHelper.getWritableDatabase();
        int num = database.delete("userinfo", "user_name=?", new String[]{name});
        database.close();
        return num;
    }

    public int update(String name, String pwd, String nick) {
        SQLiteDatabase database = sqLiteHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("user_pwd", pwd);
        values.put("user_nick", nick);
        int num = database.update("userinfo", values, "user_name=?", new String[]{name});
        database.close();
        return num;
    }

    public List<UserInfo> query(String name) {
        List<UserInfo> infoList = new ArrayList<UserInfo>();
        SQLiteDatabase database = sqLiteHelper.getWritableDatabase();
        Cursor cursor = database.query("userinfo", null, "user_name=?", new String[]{name}, null,
                null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                UserInfo info = new UserInfo();
                info.setUser_name(cursor.getString(1));
                info.setUser_pwd(cursor.getString(2));
                info.setUser_nick(cursor.getString(3));
                infoList.add(info);
            }
        }
        cursor.close();
        database.close();
        return infoList;
    }
}
